// tiene conto della richiesta corrente per non sovrapporne due
var currentRequest = null;

/*
* Oggetto, parser AJAX per file rss 2.0 e Atom
*/
function XParser(fileName, isXml) 
{
    var oThis = this;
    this.title = this.link = this.description = this.copyright = this.generator = this.modified = this.author = new XParserElement();
    this.items = [];
    this.onload = null;
    // Se viene passata una stringa xml
    if (isXml) {
        this.load(fileName);
    }
    // Se viene passato un path o un URL
    else 
    {
    	if(currentRequest != null) {
    		currentRequest.abort();
    		currentRequest = null;
    	}
        var req = Ajax.createXMLHttpRequest();
        currentRequest = req;
        req.onreadystatechange = function () 
        {
            if (req.readyState == 1) {
                oThis.partialLoadFeed();
            }
            if (req.readyState == 3) { }
            if (req.readyState == 4) 
            {
                if (req.status == 200) {
                    oThis.load(req.responseText);
                }
                else if (req.status == 404) 
                {
                    reportItemError("Could not retrieve RSS. Maybe the feed doesn't exist anymore! Try to subscribe again");
                }
                else if (req.status == 500)
                {
                    reportItemError("There was an internal server error while processing your request. Report this bug!");
                }
            }
        };
        req.open("get", fileName, true);
        req.setRequestHeader("Cache-control", "no-cache");
        req.setRequestHeader("Content-type", "text/xml");
        req.send(null);
    }
}
/*
*
*
*/
XParser.prototype.load = function (sXml) 
{
    // inizio creando il documento che andrò a riempire con i dati ricevuti dalla richiesta asincrona
    var xmlDom = Ajax.createDocument();
    var oThis = this;
    if (sXml.toLowerCase().indexOf("error: 500") > - 1) {
        reportItemError("Could not retrieve RSS. Maybe connection is down!");
        return false;
    }
    try 
    {
        // GECKO
        var p = new DOMParser();
        xmlDom = p.parseFromString(sXml, "text/xml");
        oThis.root = xmlDom.documentElement;
    }
    catch (e) 
    {
        // IE
        //alert("exec");
        xmlDom.loadXML(sXml);
        oThis.root = xmlDom.documentElement;
        //alert(oThis.root);
    }
    // supportiamo solo RSS 2.0 e Atom
    oThis.isRSS = (oThis.root.tagName.toLowerCase() == "rss");
    if (oThis.isRSS && parseInt(oThis.root.getAttribute("version")) < 2) {
        throw new Error("RSS version less than 2!");
    }
    oThis.isAtom = (oThis.root.tagName.toLowerCase() == "feed");
    oThis.type = (oThis.isRSS) ? "RSS" : "Atom";
    // punto di partenza comune tra standard RSS e Atom
    var ch = (oThis.isRSS) ? oThis.root.getElementsByTagName("channel")[0] : oThis.root;
    // inizio il parsing del documento xml con uno switch tra i tag a seconda del loro nome
    // riempio di conseguenza i campi dati del parser con i valori corretti
    for (var i = 0; i < ch.childNodes.length; i++) 
    {
        var oNode = ch.childNodes[i];
        if (oNode.nodeType == 1) 
        {
            switch (oNode.tagName.toLowerCase()) 
            {
                case "title" :
                    oThis.title = new XParserElement(oNode);
                    break;
                case "link" :
                    if (oThis.isAtom) 
                    {
                        if (oNode.getAttribute("href")) {
                            oThis.link = new XParserElement(oNode, oNode.getAttribute("href"));
                        }
                        else {
                            oThis.link = new XParserElement(oNode);
                        }
                    }
                    break;
                case "copyright" :
                    oThis.copyright = new XParserElement(oNode);
                    break;
                case "generator" :
                    oThis.generator = new XParserElement(oNode);
                    break;
                    // RSS
                case "description" :
                    oThis.description = new XParserElement(oNode);
                    break;
                case "lastbuilddate" :
                    oThis.modified = new XParserElement(oNode);
                    break;
                case "managingeditor" :
                    oThis.author = new XParserElement(oNode);
                    break;
                    // Atom
                case "tagline" :
                    oThis.description = new XParserElement(oNode);
                    break;
                case "modified" :
                    oThis.modified = new XParserElement(oNode);
                    break;
                case "author" :
                    oThis.author = new XParserElement(oNode);
                    break;
                default:
                    break;
            }
        }
    }
    var feeds = null;
    if (oThis.isRSS) {
        feeds = ch.getElementsByTagName("item");
    }
    else 
    {
        try 
        {
            xmlDom.setProperty("Selection Language", "XPath");
            xmlDom.setProperty("SelectionNamespaces", "xmlns:atom='http://www.w3.org/2005/Atom'");
            feeds = xmlDom.selectNodes("/atom:feed/atom:entry");
        }
        catch (e) {
            feeds = xmlDom.getElementsByTagName("entry");
        }
    }
    for (var i = 0; i < feeds.length; i++) {
        oThis.items[i] = new XParserItem(feeds[i]);
    }
    if (typeof this.onload == "function") 
    {
        this.onload();
    }
}
// Rappresenta un attributo di un Elemento
function XParserAttribute(oNode) 
{
    this.value = oNode.nodeValue;
}
// Rappresenta un elemento XML
function XParserElement(oNode, oValue) 
{
    this.node = oNode ? oNode : false;
    // SOLO FIREFOX per colpa di firstChild
    this.value = oValue || (this.node && Ajax.getText(this.node)) || false;
    if (this.node) 
    {
        this.attributes = [];
        var oAtts = this.node.attributes;
        for (var i = 0; i < oAtts.length; i++) 
        {
            this.attributes[i] = new XParserAttribute(oAtts[i]);
            this.attributes[oAtts[i].nodeName] = new XParserAttribute(oAtts[i]);
        }
    }
    else {
        this.attributes = false;
    }
    this.isNull = (!this.node && !this.value && !this.attributes);
}
// Rappresenta un post di un feed
function XParserItem(itemNode) 
{
    this.title = this.link = this.author = this.description = this.date = new XParserElement();
    for (var i = 0; i < itemNode.childNodes.length; i++) 
    {
        var oNode = itemNode.childNodes[i];
        if (oNode.nodeType == 1) 
        {
            switch (oNode.tagName.toLowerCase()) 
            {
                case "title" :
                    this.title = new XParserElement(oNode);
                    break;
                case "link" :
                    if (oNode.getAttribute("href")) {
                        this.link = new XParserElement(oNode, oNode.getAttribute("href"));
                    }
                    else {
                        this.link = new XParserElement(oNode);
                    }
                    break;
                case "author" :
                    this.author = new XParserElement(oNode);
                    break;
                    // Tag RSS
                case "description" :
                    this.description = new XParserElement(oNode);
                    break;
                case "pubdate":
                    this.date = new XParserElement(oNode);
                    break;
                    // Atom
                case "content" :
                    this.description = new XParserElement(oNode);
                    break;
                case "summary" :
                    this.description = new XParserElement(oNode);
                    break;
                case "modified" :
                    this.date = new XParserElement(oNode);
                    break;
                case "updated" :
                    this.date = new XParserElement(oNode);
                    break;
                case "issued" :
                    this.date = new XParserElement(oNode);
                    break;
                default:
                    break;
            }
        }
    }
}
// metodo di Xparser per mostrare all'utente il caricamento
XParser.prototype.partialLoadFeed = function () 
{
    var img = document.createElement("img");
    img.src = "../images/ajax-loader.gif";
    img.setAttribute("alt", " ");
    var par = document.createElement("p");
    par.id = "loading";
    var tn = document.createTextNode("Loading feed...");
    var br = document.createElement("br");
    var cont = document.getElementById("feed_items_wrapper");
    if (document.getElementById("he") != null) {
        cont.removeChild(document.getElementById("he"));
    }
    if (document.getElementById("loading") != null) {
        cont.removeChild(document.getElementById("loading"));
    }
    var t = document.getElementById("item_list");
    if (t != null) {
        cont.removeChild(t);
    }
    par.appendChild(img);
    par.appendChild(br);
    par.appendChild(tn);
    cont.appendChild(par);
}
function reportItemError(err) 
{
    var cont = document.getElementById("feed_items_wrapper");
    if (document.getElementById("loading") != null) {
        cont.removeChild(document.getElementById("loading"));
    }
    var he = document.createElement("p");
    he.id = "he";
    he.className = "error";
    var er = document.createTextNode(err);
    he.appendChild(er);
    cont.appendChild(he);
}
